package com.dream.inspect.modules.business.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dream.inspect.common.utils.DatetimeUtil;
import com.dream.inspect.common.utils.PageUtils;
import com.dream.inspect.common.utils.Query;
import com.dream.inspect.common.utils.StringUtil;
import com.dream.inspect.modules.business.common.CommonComponent;
import com.dream.inspect.modules.business.common.CommonUtil;
import com.dream.inspect.modules.business.dao.SuperviseQuestionDao;
import com.dream.inspect.modules.business.dao.SuperviseStandardDao;
import com.dream.inspect.modules.business.dao.SuperviseTempletDao;
import com.dream.inspect.modules.business.entity.SuperviseStandardEntity;
import com.dream.inspect.modules.business.entity.SuperviseTempletEntity;
import com.dream.inspect.modules.business.service.SuperviseStandardService;
import com.dream.inspect.modules.sys.dao.SysDeptDao;
import com.dream.inspect.modules.sys.entity.SysDeptEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@Service("superviseStandardService")
public class SuperviseStandardServiceImpl extends ServiceImpl<SuperviseStandardDao, SuperviseStandardEntity> implements SuperviseStandardService {
    private ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    @Autowired
    private CommonComponent commonComponent;
    @Autowired
    SysDeptDao sysDeptDao;
    @Autowired
    SuperviseTempletDao superviseTempletDao;
    @Autowired
    SuperviseQuestionDao superviseQuestionDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<SuperviseStandardEntity> page = this.selectPage(
                new Query<SuperviseStandardEntity>(params).getPage(),
                new EntityWrapper<SuperviseStandardEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SuperviseStandardEntity> findAllDesc() {

        return baseMapper.findAllListDesc();
    }

    @Override
    public List<SuperviseStandardEntity> findStandardType(Map<String, Object> params) {
        EntityWrapper<SuperviseStandardEntity> wrapper = new EntityWrapper<SuperviseStandardEntity>();
        wrapper.setEntity(new SuperviseStandardEntity());
        wrapper.eq("level_num", "1");
        List<SuperviseStandardEntity> dataList = this.selectList(wrapper);
        return dataList;
    }

    @Override
    public List<Map<String, Object>> getListByCode(String code, String level, String name) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        list = baseMapper.getList(code, level, name);
        return list;
    }

    @Override
    public List<SuperviseStandardEntity> findListByCodeAndLevel(Map<String, Object> params) {
        String code = null;
        String level = "1";
        String name = null;
        if (params.get("level") != null && !"1".equals(params.get("level"))) {
            level = params.get("level").toString();
            if (StringUtil.isNotEmpty(params.get("code") + "")) {
                code = params.get("code").toString();
            }
            if (StringUtil.isNotEmpty(params.get("name") + "")) {
                code = params.get("name").toString();
            }
        }
        int childrenNum = 0;
        List<SuperviseStandardEntity> list = new ArrayList<SuperviseStandardEntity>();
        list = baseMapper.findListByCodeAndLevel(code, level, name);
        List<SuperviseStandardEntity> standardEntityList = new ArrayList<SuperviseStandardEntity>(10);
        if (CommonUtil.LEVEL_3.equals(params.get("level"))) {
            for (SuperviseStandardEntity standardEntity : list) {
                List<SuperviseStandardEntity> standardList = baseMapper.findListByCodeAndLevel(standardEntity.getSbdm(), "4", null);
                if (standardList != null) {
                    childrenNum = standardList.size();
                }
                standardEntity.setChildrenNum(childrenNum);
                standardEntityList.add(standardEntity);
            }
        } else {
            standardEntityList = list;
        }
        return standardEntityList;
    }

    @Override
    public List<SuperviseStandardEntity> findAllListTree() {

        List<SuperviseStandardEntity> list = baseMapper.findAllListDesc();
    /*for(int i =1 ;i<= 10 ;i++){
        Map<String, Object> temp = new HashMap<String, Object>();
        temp.put("id", i);
        if(i != 1){
            temp.put("parentId", (int)Math.random()*10 + 1);
        }
        temp.put("children", new ArrayList<Map<String,Object>>());
        list.add(temp);
    }*/

        Map<Long, Object> map = new HashMap<Long, Object>();
        for (SuperviseStandardEntity t : list) {
            map.put(t.getId(), t);
        }

        List<SuperviseStandardEntity> result = new ArrayList<SuperviseStandardEntity>();
        for (int i = 0; i < list.size(); i++) {
            SuperviseStandardEntity temp2 = list.get(i);
            if (null != map.get(temp2.getParentId())) {
                (((SuperviseStandardEntity) map.get(temp2.getParentId())).getChildren()).add(temp2);
                /*result.remove(i);
				i--;*/
                continue;
            } else {
                result.add(temp2);
            }
        }
        return result;
    }

    @Override
    public List<SuperviseStandardEntity> findStandardListByParentId(Map<String, Object> params) {
        return baseMapper.findListByParentId(params);
    }

    @Override
    public List<SuperviseStandardEntity> findAllList() {
        //String level = "1";
        Map<String, Object> map = new HashMap<String, Object>(1);
        map.put("parentId", "0");
        List<SuperviseStandardEntity> list = baseMapper.findListByParentId(map);
        List<SuperviseStandardEntity> standardEntityList = new ArrayList<SuperviseStandardEntity>(10);
        for (SuperviseStandardEntity standardEntity : list) {
            getSuperviseStandardChildren(standardEntity, "1");
            standardEntityList.add(standardEntity);
        }
        return standardEntityList;
    }

    /**
     * 递归获取问题
     *
     * @param superviseStandardEntity
     * @param level
     */
    private void getSuperviseStandardChildren(SuperviseStandardEntity superviseStandardEntity, String level) {
        List<SuperviseStandardEntity> treesParent = new ArrayList<SuperviseStandardEntity>();
        if (CommonUtil.LEVEL_3.equals(superviseStandardEntity.getLevelNum())) {
            return;
        }
        Map<String, Object> map = new HashMap<String, Object>(1);
        map.put("parentId", superviseStandardEntity.getId());
        List<SuperviseStandardEntity> superviseStandardEntitieList = baseMapper.findListByParentId(map);
        if (superviseStandardEntitieList != null) {
            superviseStandardEntity.setChildrenNum(superviseStandardEntitieList.size());
        }
        for (SuperviseStandardEntity treeNode : superviseStandardEntitieList) {
            getSuperviseStandardChildren(treeNode, level);
            treesParent.add(treeNode);
        }
        superviseStandardEntity.setChildren(treesParent);
    }

    @Override
    public Map<String, Object> findNextInfo(Map<String, Object> params) {
        String level = params.get("level")+"";
        String code = params.get("code")+"";
        long deptId = (long) params.get("deptId");
        SysDeptEntity sysDeptEntity = sysDeptDao.selectById(deptId);
        Map<String, Object> standardEntity = new HashMap<String, Object>();
        String newCode = commonComponent.getNextCode(level, code);
        standardEntity.put("code", newCode);
        standardEntity.put("deptLevel", CommonUtil.getStandardLevel(sysDeptEntity));
        standardEntity.put("deptName", sysDeptEntity.getName());
        standardEntity.put("createTime", new Date());
        return standardEntity;
    }


    @Override
    public void addEntity(SuperviseStandardEntity superviseStandard) {
        SysDeptEntity sysDeptEntity = sysDeptDao.selectById(superviseStandard.getDeptId());
        superviseStandard.setCreateTime(new Date());
        String newCode = null;
        if (CommonUtil.LEVEL_1.equals(superviseStandard.getLevelNum())) {
            newCode = commonComponent.getNextCode(superviseStandard.getLevelNum(), null);
            superviseStandard.setYjmldm(newCode);
            superviseStandard.setYjmlmc(superviseStandard.getQuestionDescription());
        } else if (CommonUtil.LEVEL_2.equals(superviseStandard.getLevelNum())) {
            newCode = commonComponent.getNextCode(superviseStandard.getLevelNum(), superviseStandard.getYjmldm());
            superviseStandard.setEjmldm(newCode);
            superviseStandard.setEjmlmc(superviseStandard.getQuestionDescription());
        } else if (CommonUtil.LEVEL_3.equals(superviseStandard.getLevelNum())) {
            newCode = commonComponent.getNextCode(superviseStandard.getLevelNum(), superviseStandard.getEjmldm());
            superviseStandard.setSjmldm(newCode);
            superviseStandard.setSjmlmc(superviseStandard.getQuestionDescription());
        } else if (CommonUtil.LEVEL_4.equals(superviseStandard.getLevelNum())) {
            newCode = commonComponent.getNextCode(superviseStandard.getLevelNum(), superviseStandard.getSjmldm());
        }
        superviseStandard.setStatus("0");
        superviseStandard.setbLevel(CommonUtil.getStandardLevelNum(sysDeptEntity));
        superviseStandard.setSbdm(newCode);
        insert(superviseStandard);
        if (CommonUtil.LEVEL_1.equals(superviseStandard.getIsGenerateStandardTemplate())) {
            //生成标准模板
            cachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    addTempletEntity(superviseStandard);
                    //templetEntity.setQh(superviseStandard);
                    //System.out.println("生成标准模板" + superviseStandard.toString());
                }
            });
        }
    }

    /**
     * 添加标准模板
     *
     * @param superviseStandard
     */
    public void addTempletEntity(SuperviseStandardEntity superviseStandard) {
        Map<String, Object> param = new HashMap<String, Object>();

      /*  SuperviseStandardEntity superviseStandardEntity = new SuperviseStandardEntity();
        superviseStandardEntity.setYjmldm(superviseStandard.getYjmldm());
        superviseStandardEntity=baseMapper.selectOne(superviseStandardEntity);*/
        param.put("deptIds", commonComponent.findParentIds(superviseStandard.getDeptId()));
        param.put("yjmldm", superviseStandard.getYjmldm());
        List<SuperviseStandardEntity> list = baseMapper.findListByIds(param);
        StringBuffer standardIds = null;
        for (SuperviseStandardEntity standardEntity : list) {
            if (standardIds != null) {
                standardIds.append(",");
            } else {
                standardIds = new StringBuffer("");
            }
            standardIds.append(standardEntity.getId());
        }
        SysDeptEntity sysDeptEntity = sysDeptDao.selectById(superviseStandard.getDeptId());
        String standardType = CommonUtil.getModelLevelNum(superviseStandard.getYjmldm());
        Map<String, Object> map = new HashMap<String, Object>(3);
        map.put("standardType", standardType);
        map.put("deptId", sysDeptEntity.getDeptId());
        map.put("time", DatetimeUtil.getDateyyyyMMddhhmmss());
        superviseTempletDao.updateDisuseFlag(map);
        SuperviseTempletEntity templetEntity = new SuperviseTempletEntity();
        templetEntity.setDeptId(superviseStandard.getDeptId());
        templetEntity.setCreateUser(superviseStandard.getCreateUser());
        templetEntity.setCreateTime(new Date());
        templetEntity.setQh(sysDeptEntity.getQhId() + "");
        templetEntity.setLevel(CommonUtil.getModeLevel(sysDeptEntity));
        templetEntity.setMblx("0");
        templetEntity.setMbwtx(standardIds.toString());
        templetEntity.setShijdm(sysDeptEntity.getName());
        templetEntity.setMbmc(superviseStandard.getYjmlmc() + "标准模板");
        templetEntity.setStandardType(standardType);
        superviseTempletDao.insert(templetEntity);
        addStandardTemplateRecursion(superviseStandard.getDeptId(), superviseStandard);
    }


    /**
     * 新增标准模板循环递归
     *
     * @param parentId
     */
    public void addStandardTemplateRecursion(long parentId, SuperviseStandardEntity superviseStandardEntity) {
        List<Long> deptIdList = sysDeptDao.queryDetpIdList(parentId);
        for (Long deptId : deptIdList) {
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("deptIds", deptId);
            List<SuperviseStandardEntity> list = baseMapper.findListByIds(param);
            if (list != null && list.size() > 0) {
                superviseStandardEntity.setDeptId(deptId);
                cachedThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        addTempletEntity(superviseStandardEntity);
                    }
                });
            }
        }
    }

    @Override
    public Map<String, Object> getQuestionCount(Map<String, Object> param) {
        List<Map<String, Object>> list = superviseQuestionDao.getQuestionCountByStandardId(param.get("standardId") + "");
        Map<String, Object> countMap = new HashMap<String, Object>();
        if (list != null && list.size() > 0) {
            countMap = list.get(0);
        }
        return countMap;
    }
    /*SELECT
    (select count(1) from supervise_question where TO_DCDW IS NOT NULL AND MODIFY_STATUS !=2 ) all_num,
		QUESTION_ID,
		sum(num) QUESTION_num,
		count(to_id) repeat_num,
		sum(to_id) repeat_num_n
	FROM
		(
			SELECT
				TO_DCDW,
				count(1) num,
				CASE WHEN count(1) > 1 THEN count(1) ELSE NULL END to_id,
				QUESTION_ID
			FROM
				supervise_question
			WHERE
				1 = 1
		AND TO_DCDW IS NOT NULL
		AND MODIFY_STATUS !=2 and QUESTION_ID = 4
		GROUP BY
			TO_DCDW,QUESTION_ID
		) a
GROUP BY
	QUESTION_ID*/
}
